package com.facemox.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.facemox.bean.GlobalParameter;
import com.facemox.service.GlobalParameterService;

@RestController
public class GlobalParameterController {
    
    @Autowired
    private GlobalParameter globalParameter;
    
    @Autowired
    private GlobalParameterService globalParameterService;
    
    Map<String,Object> map = new HashMap<String, Object>();
    
    @RequestMapping("add_global_parameter")
    public int addGlobalParameter(HttpServletRequest request) {
        map.clear();
        Enumeration<String> gps = request.getParameterNames();
        while(gps.hasMoreElements()) {
            String globalParameter = gps.nextElement();
            String[] parameterValues = request.getParameterValues(globalParameter);
            map.put(parameterValues[0].trim(), parameterValues[1].trim());
        }
        
        // Map转JSON
        String globalParameterStr = JSONArray.toJSONString(map);
        
        globalParameter.setParamBody(globalParameterStr);
        
        GlobalParameter globParam = globalParameterService.getGlobalParameter();
        
        if(globParam==null) {
            int effectLine = globalParameterService.addGlobalParameter(globalParameter);
            return effectLine;
        }else {
            int effectLine = globalParameterService.UpdateGlobalParameter(globalParameter);
            return effectLine;
        }
    }
    
    
    @RequestMapping("get_global_parameter")
    public Object getGlobalParameter() {
        GlobalParameter globalParameter = globalParameterService.getGlobalParameter();
        JSONObject globalParamMap = null;
        if(globalParameter!=null) {
            
            String paramBody = globalParameter.getParamBody();
            // JSON转Map
            globalParamMap = JSON.parseObject(paramBody);
            
        }else {
            return "";
        }
        return globalParamMap;
    }
    
}
